﻿using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using WebMvc.Models;
 
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web;
using System.Linq;
using System;
using DoMain.IdentityUsers;
using DoMain.IdentityUserLogins;
using DoMain.IdentityUserClaims;

namespace WebMvc.Controllers
{
    public class AccountController : Controller
    {
        private IIdentityUserRepository _userRepo;
        private IIdentityUserLoginRepository _userLoginRepo;
        private IIdentityUserClaimRepository _userClaimRepo;

        public AccountController(IIdentityUserRepository userRepo, IIdentityUserLoginRepository userLoginRepo, IIdentityUserClaimRepository userClaimRepo)
        {
            _userRepo = userRepo;
            _userLoginRepo = userLoginRepo;
            _userClaimRepo = userClaimRepo;
             UserManager = new UserManager<IdentityUser>(new MyUserStore(_userRepo, _userLoginRepo,userClaimRepo));
        }


        public UserManager<IdentityUser> UserManager { get; private set; }

        [AllowAnonymous]        
        public ActionResult Index()
        {
            Response.Headers["Authorizatio"] = "诡异的jwt";
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
         
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            var jwt = Request.Headers["Authorizatio"];
            var s = Request.Headers[""];

            var user = new IdentityUser();
            if (ModelState.IsValid)
            {
                user = await UserManager.FindAsync(model.UserName, model.Password);
                var token = new TokenController().GetToken(model.UserName, model.Password, DateTime.Now.AddDays(1));
                Response.Headers.Set("Authorizatio", token);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }

            }
            ViewBag.Model = Newtonsoft.Json.JsonConvert.SerializeObject(user);
         
            // If we got this far, something failed, redisplay form
            return View("Index");
        }

        //
        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                
                var manager = UserManager;
                var user = new IdentityUser() { UserName = model.UserName, PasswordHash=model.Password };

                IdentityResult result =await manager.CreateAsync(user, user.PasswordHash);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    // Response.Redirect("~/Login.aspx");

                    if (User.Identity.IsAuthenticated)
                    {
                        ViewBag.StatusMessage= "欢迎您：" + User.Identity.Name;
                         
                    }


                }
                else
                {
                    ViewBag.StatusMessage  = result.Errors.FirstOrDefault();
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register2(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser() { UserName = model.UserName, PasswordHash = model.Password };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }

        

        #region 辅助

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private async Task SignInAsync(IdentityUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }
        #endregion


    }
}